<?php

// No direct access to this file
defined('_JEXEC') or die('Restricted access');
JTable::addIncludePath(JPATH_COMPONENT.DIRECTORY_SEPARATOR.'tables');

class KetnoiModelDonvi extends JModelLegacy
{
	public function getTable($type = 'Donvi', $prefix = 'KetnoiTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	function loadGridData($limitstart,$limit,$where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("*");
        $query->from("#__donvi");
        $query->where($where);
        $query .= " limit $limitstart,$limit";  
        $db->setQuery($query);
        $result = $db->loadObjectList();
        return $result; 
    }
    
	function loadAllGridData($where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)");
        $query->from("#__donvi");
        $query->where($where); 
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result; 
    }
    
    public function getAllDonvi()
    {
    	$db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("*");
        $query->from("#__donvi");
        $query->where("is_delete = 0");
        $db->setQuery($query);
        $result = $db->loadObjectList();
        return $result;
    }
    
    function save()
    {
    	global $app;
    	$table = $this->getTable();
    	$post = JRequest::get("post");
		$table = Utility::save($table, $_REQUEST);
		return $table;
    }
    
	function checkMaExists()
    {
    	$ma = JRequest::getVar("ma");
    	$oldval = JRequest::getVar("oldval","");
    	if(strtolower($ma) == strtolower($oldval))
    	{
    		return false;
    	}
    	$db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)");
        $query->from("#__donvi");
        $query->where("is_delete = 0 and ma = '$ma'");
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result > 0;
    }
    
	function checkTenExists()
    {
    	$ten = JRequest::getVar("ten");
    	$oldval = JRequest::getVar("oldval","");
    	if(strtolower($ten) == strtolower($oldval))
    	{
    		return false;
    	}
    	$db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)");
        $query->from("#__donvi");
        $query->where("is_delete = 0 and ten = '$ten'");
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result > 0;
    }
    
	function loadData($id)
	{
		$table = $this->getTable();
		$table->load($id);
		return $table;
	}
	
	function delete()
	{
		$id = JRequest::getVar("id");
		$db = JFactory::getDbo();
		//$query = "update #__user_group set is_delete = 1 where id = $id";
		$query = "update #__donvi set is_delete = 1 where id = $id";
		$db->setQuery($query);
		$db->query();
	}
}
